from typing import List, Dict
from fastapi import FastAPI, WebSocket, WebSocketDisconnect

class ConnectionManager:
    def __init__(self):
        self.active_connections: Dict[str, WebSocket] = {}

    async def connect(self, websocket: WebSocket, user_id: str):
        await websocket.accept()
        self.active_connections[user_id] = websocket

    async def disconnect(self, user_id: str):
        websocket = self.active_connections.get(user_id)
        if websocket:
            await websocket.close()
            del self.active_connections[user_id]

    async def send_personal_message(self, data: str, user_id: str):
        websocket = self.active_connections.get(user_id)
        if websocket:
            await websocket.send_text(data)

    async def broadcast(self, data: str):
        for connection in self.active_connections.values():
            await connection.send_text(data)

    async def send_personal_message_or_error(self, data: str, user_id: str, error_message: str = "User not connected"):
        if user_id in self.active_connections:
            await self.send_personal_message(data, user_id)
        else:
            await self.broadcast(error_message)


manager = ConnectionManager()


